package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.kaixinff.kaixin001.util.Filter;
import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.User;

@SuppressWarnings("serial")
public class GiftServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers(new Filter(){
			@Override
			public boolean access(User user) {
				return user.hasStep(RegStep.ADD_XW);
			}}, resp);
		if (users == null) {
			return;
		}
		
		resp.getWriter().println("<form name='form1' method='post' action='/kx/gift'>");
		resp.getWriter().println("<input type=submit name='submit' value='run'>");
		resp.getWriter().println("</form>");
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		int[][] giftThresholds = new int[][] {new int[]{70, 50}, new int[]{70, 50}, new int[]{70, 50}};
		List<User> users = KXUtil.getUsers(new Filter(){
			@Override
			public boolean access(User user) {
				return user.hasStep(RegStep.ADD_XW);
			}}, resp);
		for (User user: users) {
			KXClient client = KXClient.getInstance(user.getId());
			boolean canReveive = gift(client, "Newyearbox_Inv");
//			boolean canReveive = gift(client, giftThresholds);
			if (!canReveive) {
				break;
			}
		}
		System.out.println("赠送礼物结束！");
	}
	
	private int getCityId() {
		return 2;
	}
	
	private boolean gift(KXClient client, String id) throws IOException {
		String url = KXUtil.XW_URL + "/inventory.php?item=loot&cid=" + getCityId() + "&t=" + Math.random();
		String html = client.doGet(url, null).getContent();
		if (html.indexOf("onclick=\"XW.Inv.gift('" + id + "','tr_');\"") > -1) {
			return giftLoot(client, KXUtil.getMainUserUid(), id, 1, "");
		}
		return true;
	}
	
	private boolean gift(KXClient client, int[][] giftThresholds) throws IOException {
		String[] htmls = getLootHtmls(client, getCityId());
		Pattern p = Pattern.compile("<img.+?src=\"(.+?)\"/>.+?<b.+?class=\"f14\">(.+?)</b>.+?<div.+?title=\"攻击值\"><img.+?/>(\\d+?)</div>.+?<div.+?title=\"防御值\"><img.+?/>(\\d+?)</div>.+?<div.+?>拥有数量：<b.+?>(\\d+?)</b></div>.+?XW[.]Inv[.]gift[(]'(.+?)','tr_'[)];", Pattern.DOTALL);
		int max1 = 0;
		int max2 = 0;
		String id1 = null;
		String id2 = null;
		int num1 = 0;
		int num2 = 0;
		List<String> giftIdList = new ArrayList<String>();
		List<Integer> giftNumList = new ArrayList<Integer>();
		int[] nums = new int[giftIdList.size()];
		Map<String, Integer> attackMap = new HashMap<String, Integer>();
		Map<String, Integer> defenceMap = new HashMap<String, Integer>();
		
		for (int i = 0, n = htmls.length - 1; i < n; i++) {
			String subhtml = htmls[i];
			String[] strs = subhtml.split("<tr id=\"tr_");
			for (int i2 = 0, n2 = strs.length; i2 < n2; i2++) {
				Matcher m = p.matcher(strs[i2]);
				while (m.find()) {
					String id = m.group(6);
					int attack = Integer.parseInt(m.group(3));
					int defence = Integer.parseInt(m.group(4));
					int num = Integer.parseInt(m.group(5));
					int ii = giftIdList.indexOf(id);
					attackMap.put(id, attack);
					defenceMap.put(id, defence);
					if (ii > -1) {
						if (num >= giftNumList.get(ii)) {
							nums[ii] = num;
						}
					}
					if (attack >= giftThresholds[i][0] &&
							(attack > max1 || (attack == max1 && num > num1))) {
						max1 = attack;
						id1 = id;
						num1 = num;
					}
					if (defence >= giftThresholds[i][1] &&
							(defence > max2 || (defence == max2 && num > num2))) {
						max2 = defence;
						id2 = id;
						num2 = num;
					}
				}
			}
		}
		loadOtherItems(htmls[3], giftIdList, giftNumList, nums);
		
		String id = null;
		int num = 0;
		for (int i = 0, n = nums.length; i < n; i++) {
			if (nums[i] > 0) {
				id = giftIdList.get(i);
				num = nums[i] > 20 ? 20 : nums[i];
				break;
			}
		}
		if (id == null) {
			if (id1 != null) {
				id = id1;
				num = num1 > 20 ? 20 : num1;
			} else if (id2 != null) {
				id = id2;
				num = num2 > 20 ? 20 : num2;
			} else {
				id = "N/A";
			}
		}
		if ("N/A".equals(id)) {
			return true;
		}
		return giftLoot(client, KXUtil.getMainUserUid(), id, num, "");
	}
	
	private void loadOtherItems(String html, List<String> giftIdList, List<Integer> giftNumList, int[] nums) {
		Pattern p = Pattern.compile("XW[.]Inv[.]gift[(]'(.+?)'");
		Matcher m = p.matcher(html);
		while (m.find()) {
			String id = m.group(1);
			int ii = giftIdList.indexOf(id);
			if (ii > -1) {
				int index = m.start();
				String numhtml = "id=\"num_" + id + "\"";
				int beginIndex = html.lastIndexOf(numhtml, index);
				beginIndex = html.indexOf(">", beginIndex) + 1;
				int endIndex = html.indexOf("<", beginIndex);
				int num = Integer.parseInt(html.substring(beginIndex, endIndex));
				if (num >= giftNumList.get(ii)) {
					nums[ii] = num;
				}
			}
		}
	}
	
	private String[] getLootHtmls(KXClient client, int cid) throws IOException {
		String[] htmls = new String[4];
		String url = KXUtil.XW_URL + "/inventory.php?item=loot&cid=" + cid + "&t=" + Math.random();
		htmls[0] = client.doGet(url, null).getContent();
		url = KXUtil.XW_URL + "/!inventory.php?cat=armor&flag=list&item=loot&cid=" + cid + "&tmp=" + Math.random();
		htmls[1] = client.doGet(url, null).getContent();
		url = KXUtil.XW_URL + "/!inventory.php?cat=vehicle&flag=list&item=loot&cid=" + cid + "&tmp=" + Math.random();
		htmls[2] = client.doGet(url, null).getContent();
		url = KXUtil.XW_URL + "/!inventory.php?cat=other&flag=list&item=loot&cid=" + cid + "&tmp=" + Math.random();
		htmls[3] = client.doGet(url, null).getContent();
		return htmls;
	}
	
	private boolean giftLoot(KXClient client, String uid, String wkey, int num, String msg) throws IOException {
		String url = KXUtil.XW_URL + "/!ajax_gift.php?wkey=" + wkey + "&type=loot&num=" + num + "&msg=" + msg + "&uid=" + uid + "&flag=sendgift&cid=" + getCityId() + "&tmp=" + Math.random() + "&rt=json";
		String html = gift(client, url, uid);
		if (html.indexOf("\\u4e0d\\u80fd\\u518d\\u6536\\u793c\\u7269\\u4e86") > -1) {
			return false;
		}
		return true;
	}
	
	private String gift(KXClient client, String url, String uid) throws IOException {
		String html = client.doGet(url, null).getContent();
		try {
			JSONObject jobj = new JSONObject(html);
			if ("suc".equals(jobj.getString("flag"))) {
				System.out.println(KXUtil.findMessage(jobj.getString("html")));
			} else if ("notice".equals(jobj.getString("flag"))) {
				System.out.println(KXUtil.findMessage(jobj.getString("info")));
			} else if ("err".equals(jobj.getString("flag"))) {
				System.err.println(KXUtil.findMessage(jobj.getString("error")));
			}
		} catch (JSONException e) {
			System.err.println(html);
			e.printStackTrace();
		}
		return html;
	}
}
